// I2C_DAT has to be defined
// I2C_CLK has to be defined

#include "i2c.h"

void delay(U8 i)
{
	U16 j;
	while(i--)
	{
		j=3;
		while(j--);
	}

}

void I2C_WriteBit(unsigned char c)
{

    if (c > 0)
    {
        I2C_DAT=1;
    }
    else
    {
        I2C_DAT=0;
    }

    delay(1);
    I2C_CLOCK=1;
    delay(2);

    I2C_CLOCK=0;
    delay(3);

    /*if (c > 0)
    {
    	I2C_CLOCK=0;
    }
*/
}

U8 I2C_ReadBit()
{
	U8 retVal;
    I2C_DAT=1;
    delay(1);
    I2C_CLOCK=1;
    delay(2);
    PM6=0xfe;
    retVal = I2C_DAT;


	I2C_CLOCK=0;
    delay(1);
    PM6 = 0xfc;
    return retVal &0x01;
}

// Inits bitbanging port, must be called before using the functions below
//
void I2C_Init()
{

	//I2C_CLOCK=0;
	//I2C_DAT=0;
	I2C_CLOCK=1;
    I2C_DAT=1;

    delay(1);
}

// Send a START Condition
//
void I2C_Start()
{
	I2C_DAT=1;
    delay(1);
    I2C_CLOCK=1;
    delay(1);
	I2C_DAT=0;
    delay(1);

    I2C_CLOCK=0;
    delay(1);
}

// Send a STOP Condition
//
void I2C_Stop()
{
	I2C_DAT = 0;
	delay(1);
    I2C_CLOCK=1;
    delay(1);

    I2C_DAT=1;
    delay(1);
}

void I2C_Ack()
{

}
// write a byte to the I2C slave device
//
U8 I2C_WriteByte(U8 c)
{
	U8 i;
    for (i = 0; i < 8; i++)
    {
        I2C_WriteBit(c & 0x80);

        c <<= 1;
    }

    return I2C_ReadBit();
    //return 0;
}


// read a byte from the I2C slave device
//
unsigned char I2C_ReadByte(unsigned char ack)
{
	U8 i, res = 0;

    for (i = 0; i < 8; i++)
    {
        res <<= 1;
        res |= I2C_ReadBit();
    }

    if (ack > 0)
    {
        I2C_WriteBit(0);
    }
    else
    {
        I2C_WriteBit(1);
    }

    delay(1);

    return res;
}

unsigned char I2C_Write(U8 addr, U8 *data, U8 count, U8 stopControl)
{
	int i;
	I2C_Start();
	if(I2C_WriteByte(addr<<1))
	{
		for(i=0;i<count;i++)
		{
			I2C_WriteByte(*data++);
		}
	}
	if(stopControl)
		I2C_Stop();
}
unsigned char I2C_Read(U8 addr, U8 *data, U8 count, U8 stopControl)
{
	int i;

	I2C_Start();
	if(I2C_WriteByte(addr<<1))
	{
		for(i=0;i<count;i++)
		{
			if(i==count-1)
				*data = I2C_ReadByte(0);
			else
				*data = I2C_ReadByte(1);
			data++;
		}
	}
	if(stopControl)
		I2C_Stop();
}
